/**
 * user edit
 */
let systemType="MOVIE";
layui.use(['form', 'tableSelect'], function () {
    var form = layui.form,
        layer = layui.layer,
        tableSelect = layui.tableSelect,
        $ = layui.jquery;

    let shipId="";
    let u=localStorage.getItem("ADMIN_LOGIN");
    let loginU={};
    if(u==undefined){layer.msg('请登录', {icon: 1, time: 500},function () {window.location = 'page/login.html';});}else{loginU=decryptLocalStorage(u);}
    let _data=localStorage.getItem("userData");
    let viewData=undefined;
    let userType="1";
    let _shipNames=undefined;
    let _orgNames=undefined;
    if(_data!=undefined){
        viewData=decryptLocalStorage(_data,loginU.token);
        userType=viewData.userType;
        if(viewData.userType=='1') {
            $("#shipId").val("0");
            $("#shipName").val("-");
            $("#orgIds").val("");
            $("#orgNames").val("全部门");
        }else{
            $($(".super-admin-panel")).show();
            $("#shipId").val(viewData.shipId);
            $("#shipName").val(viewData.shipName);
            $("#orgIds").val(viewData.orgIds);
            $("#orgNames").val(viewData.orgNames);
            if(viewData.orgNames!='' && viewData.orgNames!=undefined){
                let orgNames=viewData.orgNames;
                let orgNameArray=orgNames.split(",");
                if(orgNameArray.length>0)
                {
                    let orgCodeArray=[];
                    for(let i=0;i<orgNameArray.length;i++)
                    {
                        if(orgNameArray[i]=='甲板')
                        {
                            orgCodeArray.push("01");
                        }else if(orgNameArray[i]=='轮机')
                        {
                            orgCodeArray.push("02");
                        }else if(orgNameArray[i]=='电气')
                        {
                            orgCodeArray.push("03");
                        }else{
                            orgCodeArray.push("04");
                        }
                    }
                    $("#orgNames").attr("ts-selected",orgCodeArray.join(","));
                }
            }
        }
        $("#roleId").val(viewData.roleId);
        $("#roleName").val(viewData.roleName);
        $("#userName").val(viewData.userName);
        $("#password").val(viewData.password);
        $("#shipIds").val(viewData.shipIds);
        $("#shipNames").val(viewData.shipNames);
        $("#trueName").val(viewData.trueName);
        $("#mobile").val(viewData.mobile);
        $("#remark").val(viewData.remark);
        $('input[name="userName"]').prop('disabled','disabled');
        if(viewData.sex=='男'){
            $('input[name="sex"][value="男"]').prop('checked','checked');
        }else{
            $('input[name="sex"][value="女"]').prop('checked','checked');
        }
        $("#userType").val(viewData.userType);
        $("#systemType").val(viewData.systemType);
    }else{
        $("#orgIds").val("");
        $("#orgNames").val("全部门");
    }
    loadShip();
    loadOrg(shipId);
    loadRole(systemType);
    form.render('select');
    form.render('radio');


    form.on('select(systemType)', function (data) {
        let systemType = data.value;
        $("#userType").val("");
        $("#roleId").val("");
        $("#roleName").val("");
        console.log(systemType)
        loadRole(systemType);
    });

    //监听提交
    form.on('submit(saveBtn)', function (data) {
        let params=data.field;
        params.token=loginU.token;
        params.roleId=params.userType;
        //添加
        if(viewData==undefined){
            request.add('user',JSON.stringify(params),function(result){
                if(result.code==0){
                    layer.msg('保存成功', {
                        icon: 1,
                        time: 500
                    },function () {
                        // 关闭弹出层
                        var iframeIndex = parent.layer.getFrameIndex(window.name);
                        parent.layer.close(iframeIndex);
                    });

                }else{
                    layer.msg(result.msg || '保存失败', {
                        icon: 2,
                        time: 2000
                    });
                }
            });
        }
        //修改
        else{
            params.userId=viewData.userId;
            request.update('user',JSON.stringify(params),function(result){
                if(result.code==0){
                    layer.msg('保存成功', {
                        icon: 1,
                        time: 500
                    },function () {
                        // 关闭弹出层
                        var iframeIndex = parent.layer.getFrameIndex(window.name);
                        parent.layer.close(iframeIndex);
                    });

                }else{
                    layer.msg(result.msg || '保存失败', {
                        icon: 2,
                        time: 2000
                    });
                }
            });
        }

        return false;
    });

    //船舶
    function loadShip(){
        let tableUrl="/admin/v1/ship/page?shipStatus=营运&token="+loginU.token+"&shipId="+shipId;
        tableSelect.render({
            elem: '#shipNames',
            checkedKey: 'id',
            searchFlag:true,
            searchKey: 'shipName',
            table: {
                url: tableUrl,loginUserType:loginU.userType,
                cols: [[
                    { type: 'checkbox' },
                    {field: 'shipId', title: 'ID'},
                    {field: 'shipCompanyName', title: '船舶公司'},
                    {field: 'shipName', title: '船舶'}
                ]]
            },
            done: function (elem, data) {
                if(data.data.length>0)
                {
                    let shipIds=$("#shipIds").val();
                    let shipNames=$("#shipNames").val();
                    let shipIdArray = [];
                    let shipNameArray=[];
                    if(shipIds!='' && shipNames!='')
                    {
                        shipIdArray=shipIds.split(",");
                        shipNameArray=shipNames.split(",");
                    }
                    layui.each(data.data, function (index, ship) {
                        let shipId=ship.shipId;
                        let shipName=ship.shipName;
                        shipIdArray.push(shipId);
                        shipNameArray.push(shipName);
                    });

                    $("#shipIds").val(shipIdArray.join(","));
                    $("#shipNames").val(shipNameArray.join(","));
                    $($(".super-admin-panel")[1]).show();
                    $($(".super-admin-panel")[2]).show();
                    $("#orgIds").val("0");
                    $("#orgNames").val("");
                    if(shipNameArray.length>1)
                    {
                        // $("#orgNames").attr("disabled","disabled");
                    }else{
                        shipId=data.data[0].shipId;
                        // $("#orgNames").removeAttr("disabled");
                    }
                    $("#orgIds").val("0");
                    $("#orgNames").val("全部门");
                    loadOrg(shipId);
                }
            },
            clear: function () {
                shipId="";
                $("#shipIds").val("");
                $("#shipNames").val("");
                $($(".super-admin-panel")[1]).show();
                $($(".super-admin-panel")[2]).show();
                $("#orgIds").val("0");
                $("#orgNames").val("全部门");
                loadOrg(shipId);

            }
        })
    }

    //部门
    function loadOrg(shipId){
        // let orgTableUrl="/admin/v1/org/page?token="+loginU.token;
        let orgTableUrl="../../api/org.json";
        tableSelect.render({
            elem: '#orgNames',
            checkedKey: 'orgCode',
            table: {
                url: orgTableUrl,
                where: {
                    keyWork: JSON.stringify({shipId:shipId})
                },
                cols: [[
                    { type: 'checkbox' },
                    // {field: 'orgId', title: 'ID'},
                    {field: 'orgName', title: '部门名称'},
                    {field: 'orgCode', title: '部门编码'}
                ]]
            },
            done: function (elem, data) {
                if(data.data.length>0)
                {
                    if(data.data.length==4)
                    {
                        $("#orgIds").val("");
                        $("#orgNames").val("全部门");
                        $("#orgNames").attr("ts-selected","01,02,03,04");
                        return;
                    }
                    let orgIdArray = [];
                    let orgNameArray=[];
                    let orgCodeArray=[];
                    layui.each(data.data, function (index, org) {
                        let orgId=org.orgId;
                        let orgName=org.orgName;
                        let orgCode=org.orgCode;
                        orgIdArray.push(orgId);
                        orgNameArray.push(orgName);
                        orgCodeArray.push(orgCode);
                    });
                    $("#orgIds").val(orgIdArray.join(","));
                    $("#orgNames").val(orgNameArray.join(","));
                    $("#orgNames").attr("ts-selected",orgCodeArray.join(","));
                }
            },
            clear: function () {
                $("#orgIds").val("");
                $("#orgNames").val("全部门");
            }
        })
    }

    //角色
    function loadRole(systemType){
        let roleTableUrl="/admin/v1/role/page?systemType="+systemType+"&token="+loginU.token;
        tableSelect.render({
            elem: '#roleName',
            checkedKey: 'id',
            table: {
                url: roleTableUrl,
                where: {
                    keyWork: JSON.stringify({})
                },
                cols: [[
                    { type: 'radio' },
                    {field: 'roleId', title: 'ID'},
                    {field: 'systemType', align:"center", title: '系统名称', sort: true,
                        templet: function (data) {
                            if (data.systemType =='MOVIE') {
                                return "船端影音系统";
                            }else {
                                return "其他"
                            }
                        }
                    },
                    {field: 'roleName', title: '角色'},
                    {field: 'roleMenuCount', title: '是否分配菜单',
                        templet : function(data) {
                            if(data.roleMenuCount>0)
                            {
                                return "是";
                            }else{
                                return "否"
                            }
                        }}
                ]]
            },
            done: function (elem, data) {
                if(data.data.length>0)
                {
                    if(data.data[0].roleMenuCount==0){
                        layer.msg('不能选择未分配菜单的角色', {
                            icon: 2,
                            time: 5000
                        });
                        return;
                    }
                    $("#userType").val(data.data[0].roleId);
                    $("#roleId").val(data.data[0].roleId);
                    $("#roleName").val(data.data[0].roleName);

                }
            },
            clear: function () {
                $("#userType").val("");
                $("#roleId").val("");
                $("#roleName").val("");
            }
        })
    }
});